import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from 'axios'

export const fetchAboutData = createAsyncThunk('fetchData/about',async(payload,{dispatch,getState})=>{
  let res = await axios("http://codercba.com:1888/airbnb/api/home/goodprice")
  // return 匹配下面extraReducers用法
  // return res.data

  // 如果不return，那么将不使用extraReducers，而是使用reducers
  dispatch(changeList(res.data.list))
})

const aboutReducer = createSlice({
  name:'about',
  initialState:{ 
    title:'about',
    list:[]
  },
  reducers:{
    changeTitle(state,action){
      state.title = action.payload
    },
    changeList(state,action){
      state.list = action.payload
    }
  },
  // extraReducers:(builder) =>{
  //   builder.addCase(fetchAboutData.pending,(state,action)=>{
  //     console.log('pending')
  //     state.list = []
  //   }).addCase(fetchAboutData.fulfilled,(state,action)=>{
  //     console.log('fulfilled')
  //     state.list = action.payload.list
  //   }).addCase(fetchAboutData.rejected,(state,action)=>{
  //     console.log('rejected')
  //     state.list = []
  //   })
  // }
  // 已弃用
  // extraReducers:{
  //   [fetchAboutData.fulfilled]:(state,action)=>{
  //     state.list = action.payload.list
  //   }
  // }
})

export const { changeTitle,changeList } = aboutReducer.actions
export default aboutReducer.reducer